import 'package:awak/common/models/topic.dart';
import 'package:awak/common/repository/topic_repository.dart';

/// 全局主题数据持有者
/// 用于在页面间传递当前选中的主题信息
class TopicDataHolder {
  static Topic? currentTopic;
  static int? currentTopicId = 1; // 当前显示的主题ID，默认显示第一个哲学主题
  static List<Topic> allTopics = []; // 所有主题列表
  static Set<int> joinedTopicIds = {}; // 用户已加入的主题ID集合
  static Map<int, int> topicPeopleCache = {}; // 缓存主题人数，类似评论数据的缓存
  static final TopicRepository _topicRepository = TopicRepository();

  // 获取推荐主题列表（除了当前显示的主题）
  static List<Topic> getRecommendationTopics() {
    return allTopics.where((topic) => topic.id != currentTopicId).toList();
  }

  // 根据ID获取主题
  static Topic? getTopicById(int id) {
    try {
      final topic = allTopics.firstWhere((topic) => topic.id == id);
      // 如果缓存中有更新的人数，使用缓存的人数
      if (topicPeopleCache.containsKey(id)) {
        return topic.copyWith(numberPeople: topicPeopleCache[id]!);
      }
      return topic;
    } catch (e) {
      return null;
    }
  }

  // 检查用户是否已加入某个主题
  static bool isTopicJoined(int? topicId) {
    if (topicId == null) return false;
    return joinedTopicIds.contains(topicId);
  }

  // 加入主题
  static void joinTopic(int? topicId) {
    if (topicId != null) {
      joinedTopicIds.add(topicId);
    }
  }

  // 更新主题的人数（同时更新内存和数据库）
  static Future<void> updateTopicPeopleCount(int? topicId, int newCount) async {
    if (topicId == null) return;

    // 更新缓存
    topicPeopleCache[topicId] = newCount;

    // 更新allTopics中的数据
    for (int i = 0; i < allTopics.length; i++) {
      if (allTopics[i].id == topicId) {
        allTopics[i] = allTopics[i].copyWith(numberPeople: newCount);
        break;
      }
    }

    // 更新currentTopic如果是当前主题
    if (currentTopic?.id == topicId) {
      currentTopic = currentTopic!.copyWith(numberPeople: newCount);
    }

    // 异步更新数据库
    try {
      await _topicRepository.updateTopicPeople(topicId, newCount);
    } catch (e) {
      print('Error updating topic people count in database: $e');
    }
  }

  // 获取主题的最新人数（优先从缓存获取）
  static int getTopicPeopleCount(int? topicId) {
    if (topicId == null) return 0;

    // 优先从缓存获取
    if (topicPeopleCache.containsKey(topicId)) {
      return topicPeopleCache[topicId]!;
    }

    // 从allTopics获取
    final topic = allTopics.where((t) => t.id == topicId).firstOrNull;
    return topic?.numberPeople ?? 0;
  }

  // 刷新主题数据（从数据库重新加载）
  static Future<void> refreshTopicsFromDatabase() async {
    try {
      final topics = await _topicRepository.getAllTopics();
      allTopics = topics;

      // 更新缓存
      for (final topic in topics) {
        if (topic.id != null) {
          topicPeopleCache[topic.id!] = topic.numberPeople;
        }
      }

      // 更新当前主题
      if (currentTopicId != null) {
        currentTopic = getTopicById(currentTopicId!);
      }
    } catch (e) {
      print('Error refreshing topics from database: $e');
    }
  }

  // 设置当前主题（确保ID和对象同步）
  static void setCurrentTopic(Topic? topic) {
    currentTopic = topic;
    currentTopicId = topic?.id;
  }

  // 确保当前主题状态一致性
  static void ensureCurrentTopicConsistency() {
    if (currentTopicId != null && currentTopic?.id != currentTopicId) {
      // 如果ID和对象不一致，优先使用ID来获取最新数据
      currentTopic = getTopicById(currentTopicId!);
    } else if (currentTopic != null && currentTopicId != currentTopic!.id) {
      // 如果对象存在但ID不一致，更新ID
      currentTopicId = currentTopic!.id;
    }
  }
}
